package com.bbjob.service.impl;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

import org.springframework.stereotype.Service;

import com.bbjob.client.SocketUser;
import com.bbjob.job.ServerThreadDeal;

@Service
public class ServerSocketLine {

	private ServerSocket serverSocket;
	// private List<SocketUser> list = new ArrayList<SocketUser>();
	private Map<String, SocketUser> map = new HashMap<String, SocketUser>();

	public void startServer() {
		try {
			// 存放 连接上服务器的用户 列表
			serverSocket = new ServerSocket(10001);// 开启服务的端口，需和客户端一致
			System.out.println("服务端已经启动，等待客户端连接");
			while (true) {
				Socket socket = serverSocket.accept();
				SocketUser user = new SocketUser(socket.getInetAddress().getHostAddress(), socket);
				System.out.println(user.getName() + "正在登录。。。");
				// list.add(user);// 把新增的用户添加到list里面
				// System.out.println(list);
				// System.out.println("客户端的IP："
				//		+ socket.getInetAddress().getHostAddress());
				
				map.put(socket.getInetAddress().getHostAddress(), user);
				
				new ServerThreadDeal(user, map).start();// 开启输入和输出的多线程
			}
		} catch (IOException exception) {
			exception.printStackTrace();
		} finally {
			try {
				if (serverSocket != null) {
					serverSocket.close();
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	public Map<String, SocketUser> getClients() {
		// Map<String, SocketUser> map = new HashMap<String, SocketUser>();
		
		// List<String> list = new ArrayList<String>();
		
/*		for (SocketUser user : this.list) {
			map.put(user.getSocket().getInetAddress().getHostAddress(), user);
		}*/

		return map;
	}

/*	public List<SocketUser> getList() {
		return list;
	}*/
}
